<%@ page language="java" pageEncoding="UTF-8"%>
 <script>
	var _webApp = '${base}';
</script>


<script src="//cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
<script src="${base}/js/plugin/layer/layer.js"></script>

<link href="//cdn.bootcss.com/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet">

<script type="text/javascript" src="${base}/js/plugin/jquery-easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${base}/js/plugin/jquery-easyui/plugins/jquery.datagrid.js"></script>
<!--
<script type="text/javascript" src="${base}/js/plugin/jquery-easyui/plugins/datagrid-filter/datagrid-filter.js"></script>
-->

<link rel="stylesheet" href="${base}/css/plugin/pure/1.0.css">
<script type="text/javascript" src="${base}/js/plugin/jquery-easyui/plugins/jquery-easyui-datagridview/datagrid-groupview.js"></script>
<script src="${base}/js/plugin/jquery-datetimepicker/jquery.datetimepicker.js"></script>
<link rel="stylesheet" type="text/css" href="${base}/js/plugin/jquery-datetimepicker/jquery.datetimepicker.css"/>
<script src="${base}/js/plugin/jquery-easyui/locale/easyui-lang-zh_CN.js"></script>
<link rel="stylesheet" type="text/css" href="${base}/css/plugin/jquery-easyui/themes/insdep/easyui.css">
<link rel="stylesheet" type="text/css" href="${base}/css/plugin/jquery-easyui/themes/insdep/icon.css">
<script type="text/javascript" src="${base}/js/plugin/kindeditor/4.1.10/kindeditor-all-min.js"></script>
<script type="text/javascript" src="${base}/js/SelectDialog.js"></script>
<link rel="stylesheet" href="${base}/js/plugin/layer/skin/default/layer.css">
<!--layui -->
<script type="text/javascript" src="${base}/js/plugin/layui/layui.js"></script>
<link rel="stylesheet" href="${base}/js/plugin/layui/css/layui.css">



<style>
 .blue-title {
  background-color: #deebfe;
  color: #0196f0;
  padding: 0 15px;
 }
 .item-head {
  background-color: #e9e9e9;
  line-height: 35px;
  overflow: hidden;
 }
table.pvtTable tr th {
    background-color: #FFFFFF;
    border: 1px solid #CDCDCD;
    font-size: 8pt;
    padding: 5px;
}

table.pvtTable {
    font-size: 8pt;
    text-align: right;
    border-collapse: collapse;
}
.pvtAxisContainer, .pvtVals {
    border: 1px solid #B7B7B7;
    background: #FFF;
    padding: 0px;
    min-width: 20px;
    min-height: 20px;
}
tr {
    display: table-row;
    vertical-align: inherit;
    border-color: inherit;
    width:20px;
}
.pvtAggregator {
    width: 54px;
    margin-bottom:0px;
}
.pvtAttrDropdown{
	width: 54px;
}
.pvtRenderer{
	width: 54px;
}
.promotion-settings span {
    padding-right: 6px;
}
.search-bracket {
     /** background-color: #77C0F1;
     border-bottom: 1px solid #cccccc;**/
     padding: 0px 10px;
}
.promotion-settings .act-title  .sinput{
    width: 100px!important;
}

.balance-header span {
    margin-left: 5px;
    padding-left: 10px;
    border-left: 5px solid #0065d1;
    font-size: 16px;
    font-weight: 600;
}
.balance-header {
    height: 35px;
    padding-top: 15px;

}
.pagination-first {
  background: url('http://www.jeasyui.com/easyui/themes/metro/images/pagination_icons.png') no-repeat 0 center;
}
.pagination-prev {
  background: url('http://www.jeasyui.com/easyui/themes/metro/images/pagination_icons.png') no-repeat -16px center;
}
.pagination-next {
  background: url('http://www.jeasyui.com/easyui/themes/metro/images/pagination_icons.png') no-repeat -32px center;
}
.pagination-last {
  background: url('http://www.jeasyui.com/easyui/themes/metro/images/pagination_icons.png') no-repeat -48px center;
}
.pagination-load {
  background: url('http://www.jeasyui.com/easyui/themes/metro/images/pagination_icons.png') no-repeat -64px center;
}
.pagination-loading {
  background: url('http://www.jeasyui.com/easyui/themes/metro/images/loading.gif') no-repeat center center;
}
.panel-title {
  background: url('http://www.jeasyui.com/easyui/themes/metro/images/blank.gif') no-repeat;
}

.button-success,
.button-error,
.button-warning,
.button-secondary {
    color: white;
    border-radius: 4px;
    text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
}

.button-success {
    background: rgb(28, 184, 65); /* this is a green */
}

.button-error {
    background: rgb(202, 60, 60); /* this is a maroon */
}

.button-warning {
    background: rgb(223, 117, 20); /* this is an orange */
}

.button-secondary {
    background: rgb(66, 184, 221); /* this is a light blue */
}
.datagrid-toolbar .l-btn .l-btn-left .l-btn-text{
 margin:0px 0px;
}
.datagrid-header .datagrid-cell {
 /* padding: 8px 15px; */
}
.datagrid-body .datagrid-cell, .datagrid-footer .datagrid-cell {
 /* padding: 2px 15px; */
 white-space:nowrap;
 overflow:hidden;
 text-overflow:ellipsis;
}

.datagrid-header-row{
 height: 25px;
}
.datagrid-row {
 height: 23px;
}
.datagrid-toolbar{/* padding:5px 10px !important; */}

.panel-body {
 border-width: 0.5px;
 border-style: solid;
}

</style>
<%@ include file="/common/ui-tool.jsp"%>
<script>
var page = 1;
var size = 20;

Array.prototype.distinct = function(field){
    var values = []
    for(var i =0 ;i<this.length;i++){
        var row = this[i];
        if(values.length==0){
            values.push( row[field]);
        }
        var alradyHave = false;
        for(var j = 0 ;j<values.length;j++){
            if(values[j]==row[field]){
                alradyHave = true;
                break;
            }
        }
        if(alradyHave){
            continue;
        }
        values.push( row[field]);
    };
    return values;
};

KindEditor.ready(function(K) {
	editor = K.editor({
     allowFileManager : false,
     zIndex:199999999,
     uploadJson : _webApp + '/file/upload'
	});
});

var column = null;
var colMap = {};
var allData = null;
var setting = null;
var queryId = null;
var searchUrl = null;
var crudDefaultInputWidth = "280px";
var crudDialogWidth = 450;

var fixSearch = {};
function createQuery(id,columns,set,url,search){

    column = columns;

	queryId = id;
	searchUrl = url;
	setting = set;
    if(setting.pager!=null&&setting.pager){

    }else{
        setting.pager = false;
    }
    if(setting.singleSelect !=null){
        if(setting.cb==null){
            setting.cb = true;
        }
    }
	var isInit =($('#search_form').length<=0);
	var exportCheckBox = "";
	
if(isInit){

    $.each(column,function (index,row) {
        colMap[row.field] = row;
    });

	var html = "";
	if(setting.bodyTitle!=null){
		html += '<div class="item-head blue-title" style="margin-top: 5px;margin-bottom: 5px"><span class="hsize">'+setting.bodyTitle+'</span></div>';
	}

	html += '<div class="promotion-settings search-bracket" style="background-color: white"><div id="search_form">'
    html += '<a class="pure-button pure-button-primary" style="width: 100px;" id="querySearchBtn" href="javascript:search()" >搜索</a>';
    html += '<a class="pure-button pure-button-primary"  style="margin-left:25px"  id="querySearchBtn" href="javascript:window.location.reload()" >重置</a>';
    if(setting.exportBtn!=null && setting.exportBtn==true){
        html += '<a class="pure-button pure-button-primary"  style="margin-left:25px;"  id="exportBtn" href="#" >导出csv</a>';
    }
	if(setting.print!=null && setting.print){
		html += '<span class="submitbt" style="margin-left: 5px;" onclick="print()">打印</span>';
	}
	var gridSelect = "";

	if(setting.searchBar!=null && setting.searchBar.gridSelect!=null && !setting.searchBar.gridSelect){
		gridSelect = ' style="display:none" ';
	}
    html += '</div></div>' ;

    html += '<div id="container"> <div id="grid" style="margin-left:10px;width:100%;overflow-x: scroll; overflow-y: scroll;"></div></div><div id="exportSelect" style="display:none;font-size:20px;"></div><div id="crudDialog"  style="display:none;"></div><div id="pagination"></div>';
    if(setting.pager){
        html += '<div id="pager" style="background:#efefef;border:1px solid #ccc;"></div>';
    }
    $('#'+id).html(html);
	var crudDialog = '<form class="pure-form pure-form-aligned"><fieldset>';
 
	for(var i = 0 ;i < column.length;i++){
		var hidden = '';
		var disabled = "";
		var col = column[i] ;
		if(column[i].hidden || column[i].field=="caozuo"){
			hidden = 'style="display:none"';
		}
		if(col.insert || col.update){
            hidden = "";
        }
        if(col.insert ==false && col.update==false){
            hidden = 'style="display:none"';
        }
		crudDialog += '<div class="pure-control-group" '+hidden+' id="crud-'+col.field+'-div"><label style="width:7em" for="name">'+column[i].title+'</label>';
		 
		crudDialog += getInputHtml(col,crudDefaultInputWidth); 
		
		crudDialog += '</div>';
		if(column[i].search==null){
			continue;
		}
		var search = column[i].search.type;
		var searchHtml = "";
		if(search=="single"||search=="multi"){
			if(column[i].search.distinct==null){
				column[i].search.distinct = column[i].field ;
			}
			var op = "IN";
			if(search=="single"){
				op = "LIKE";
			}
			if(column[i].dialog!=null){
				op = "EQ";
			}
            if(column[i].search.op!=null){
                op = column[i].search.op;
            }

			searchHtml += '<span class="act-title">';

			if(column[i].input!=null && column[i].input.type=="radio"){

                var value = column[i].input.value;
                //searchHtml += col.title+":"
                searchHtml += ' <select id="search-'+col.field+'" name="search-'+col.field+'"   data-op="EQ"  class=" searchInput" type="text" data-type="'+column[i].search.type+'"   data-field="'+column[i].field+'"  > ';
                searchHtml += '<option value = "" ">';
                searchHtml += col.title+'</option>';
                for(var  jj = 0;jj<value.length;jj++){
                    var val = value[jj];
                    searchHtml += '<option value="'+val.value+'">';
                    searchHtml += val.text +'</option>';
                }
                searchHtml += "</select>"
                //searchHtml += val.text+'<input id="search-'+col.field+'" name="search-'+col.field+'" data-value="'+val.value+'" type="radio" data-op="EQ"  class=" searchInput" type="text" data-type="'+column[i].search.type+'"   data-field="'+column[i].field+'"   >';;

            }else{
                searchHtml += '<input id="search-'+col.field+'" placeHolder='+column[i].title+' data-op="'+op+'"  class="sinput searchInput" type="text" data-type="'+column[i].search.type+'" data-width="'+column[i].search.width+'" data-field="'+column[i].field+'"  data-distinct="'+column[i].search.distinct+'">';
            }
            searchHtml += '</span>';

		}
		if(search=="date"){
			searchHtml += '<span class="act-title"><span>'+column[i].title+':</span>';
			var initDateSearch = {start:"",end:""};
			
			if(column[i].search.value!=null){
				initDateSearch.start = addDays(new Date(),- parseInt(column[i].search.value)).format('yyyy-MM-dd')+" 00:00";
				initDateSearch.end = new Date().format('yyyy-MM-dd')+" 23:59";
			}
			 
			searchHtml += '<input value="'+initDateSearch.start+'" placeHolder="起" class="sinput searchInput" type="text" data-op="GTE" data-type="'+column[i].search.type+'" data-field="'+column[i].field+'"   data-distinct="'+column[i].search.distinct+'">~';
			
			searchHtml += '<input value="'+initDateSearch.end+'" placeHolder="止" class="sinput searchInput" type="text" data-op="LTE" data-type="'+column[i].search.type+'" data-field="'+column[i].field+'"   data-distinct="'+column[i].search.distinct+'">';
			
			searchHtml += '<select class="dateRangeSelect"><option value="">选择范围</option><option value="1">1天内</option><option value="3">3天内</option><option value="7">7天内</option><option value="15">半个月内</option><option value="30">一个月内</option><option value="90">三个月内</option><option value="183">半年内</option><option value="365">一年内</option></select>'
			searchHtml += '</span>';
		}
		$('#querySearchBtn').before(searchHtml);
	}
	crudDialog += '</fieldset></form>';
	if(setting.condition!=null){
		for(var i = 0 ; i< setting.condition.length;i++){
			var condition = setting.condition[i];
			var searchHtml = "";
			if(condition.type == "checkbox"){
				searchHtml  = '<span class="act-title">'+condition.title+'<input class="searchInput" condition="true" type="checkbox" data-type="'+condition.type+'" data-op="'+condition.op+'" data-field="'+condition.field+'"  />  </span>';
			}else if(condition.type == "text"){
				searchHtml = '<span class="act-title">'+condition.title+'<input class="searchInput" condition="true"  type="text" style="width: 100px;" data-type="'+condition.type+'" data-op="'+condition.op+'" data-field="'+condition.field+'"  />  </span>';
			}
			$('#querySearchBtn').before(searchHtml);
		}
	}
	$('#crudDialog').html(crudDialog);

	initCrudDialog(column);
	$('#querySearchBtn').parent().find('.dateRangeSelect').change(function(){
		var start = "";
		var end = "";
		if($(this).val()!=""){
			start = addDays(new Date(),- parseInt($(this).val())).format('yyyy-MM-dd')+" 00:00";
	    	end = new Date().format('yyyy-MM-dd')+" 23:59";
		}
		$(this).parent().find('input').each(function(){
			if($(this).attr('placeHolder')=="起"){
				$(this).val(start);
			}else{
				$(this).val(end);
			}
		});
	});
	if(setting.searchBar!=null){
		if(setting.searchBar.search==false){
			$('#querySearchBtn').hide(); 
		}

		if(setting.searchBar.hidden==true){
			$('#search_form').parent().hide();
		}
	}



    $('#querySearchBtn').parent().find('.searchInput').each(function(){
        var $this = $(this);
        var field = $this.data('field');
        var distinct = $this.data('distinct');
        var type = $this.data('type');
        var width = $this.data('width');
        var col = column.contains('field',field).data;
        if(width!=null){
            $this.css('width',width);
        }
        $this.on("keydown", function (e) {
            if (e.keyCode == 13) {
                $('#querySearchBtn').click();
            }
        });

        if(type=="single"||type=="multi"){
            var gridColumn = [];
            if(width == "undefined"){
                width = 300
            }
            if(url.indexOf('?')<0){
                url+="?";
            }
            if(col.dialog!=null){
                dialogHandler($this,col,"searchDialog");
            }
        }

        if(type=="date"){
            $this.css('width',300);

            $this.datetimepicker({
                startDate:$this.val(),
                lang:'ch',
                timepicker:false,
                format:'Y-m-d',
                todayButton:false
            });
        }
    });


}
//init end
 
	
	$('#exportBtn').click(function(){
		var height = 700;
		if(setting.exportBar!=null){
			if(setting.exportBar.height!=null){
				height = setting.exportBar.height;
			}
		} 
		$('#exportSelect').dialog({
			title : '数据导出',
			width : 300,
			height: height,
			buttons : [{
				text : '确认导出',
				handler : function() {
					var fields = "";
					var title = "";
					$('#exportSelect input').each(function(){
						var $input = $(this);
						if($input.prop('checked')){
							fields += $input.data('field')+",";
							title += $input.data('title')+",";
						}
					}); 
					if(fields==""){
						$.messager.alert('提示','请选择导出的字段');
						return;
					}
					var search = getSearch();
					search.title = title.substr(0,title.length-1);
					search.fields = fields.substr(0,fields.length-1);
					search.fileName = "导出数据";
					var finalUrl = url;
					if(finalUrl.indexOf('?')<0){
						finalUrl += "?";
					}
					for(key in search){
						finalUrl += key+"="+search[key]+"&";
					}
					window.open(finalUrl); 
				}
			}, {
				text : '取消',
				handler : function() {
					$('#exportSelect').dialog("close");
				}
			}]
		});  
	})
	if(setting.initSearch == null){
		setting.initSearch = true;
	}


	
	if(setting.initSearch){
		$.ajax({
	        url: url,
	        data:getSearch(),
            method:"post",
	        dataType: "json",
	        success: function(res){
	        	allData = res;
                change();
	        }
	    });
	}else{
		//$('#grid').datagrid('loadData', { total: 0, rows: [] });
	}
	 
	


	
	for(var i = 0 ;i < column.length;i++){
	    if(column[i].field=="caozuo"){
	        continue;
        }
		exportCheckBox += '<input type="checkbox" checked data-title="'+column[i].title+'" style="width: 20px;height: 20px;" data-field="'+column[i].field+'" />'+column[i].title+'<br>';
	}
	$('#exportSelect').html(exportCheckBox);

}
var editor = null;
 

function change(){

	$('#container').html('<div id="grid" style="margin-left:10px;width:100%;overflow-x: scroll; overflow-y: scroll;"></div>');

    if(!setting.pager){
         var newData = [];
         for(var i =0 ;i<allData.data.length;i++){
             if(allData.data[i].index!="合计"){
                newData.push(allData.data[i]);
             }
         }
         allData.data = newData;
    }
    initEasyUIGrid(allData.data);
	isReload = true;
}

function treeLize(node,treeGroup,tree){
	var id = node[tree.id];
	var children = treeGroup[id];
	if(children==null){
		return ;
	}
	node.children = children;
	for(var i = 0 ;i<children.length;i++){
		treeLize(children[i],treeGroup,tree);
	}
}


function initEasyUIGrid(data){
	if(setting.groupField!=null){
		setting.view = groupview; 
	}
    if(setting.pager){
        $('#pager').pagination({
            pageList :[10, 20,50,100,500,1000,2000],
            total:data.totalElements,
            pageSize:data.size,
            onSelectPage:function (a,b) {
                page = a;
                size = b;
                search()
            }
        });
        data = data.content;
    }

	var finalColumn = [];

    if( setting.cb ){
        finalColumn.push({field:'cb',checkbox : true});
    }

	if(setting.tree!=null){
		var tree = setting.tree;
		if(data!=null && data.length>0){
			if(tree.sort!=null){
				data.sorted(tree.sort,'asc');
			}
			var treeGroup = data.groupBy(tree.pid);
			var treeData = treeGroup[tree.tpid];
			if(treeData==null){
			    treeData = [];
			    for(var key in treeGroup){
			        var rows = treeGroup[key];
			        for(var i =0 ;i<rows.length;i++){
			            var row = rows[i];
                        treeData.push(row);
                    }

                }
            }
			for(var i =0 ; i<treeData.length ; i++){
				treeLize( treeData[i],treeGroup,tree);
			}

			data = treeData;
		}
	}else{

		setting.rowStyler = function(index,row){
			if(row.index!= null && row.index =='合计'){
				return 'background-color:rgb(197, 198, 206);color:#fff;font-weight:bold;';
			}
		};
	}

    if(setting.tree ==null && setting.xuhao!=false){
        finalColumn.push({field:'index',title:'',width:5,
            formatter:function(row,index,a){
                if(index.index!=null){
                    return index.index;
                }
                return a+1;
            }
        });
    }
 
	 
	for(var i = 0 ; i < column.length ; i++){
		var row = column[i];
		if(row.type=="number"){
			row.width = 70;
			row.align = 'right'; 
		}
		if(row.type=="img"){
			if(row.formatter==null){
				row.formatter = function(value,row,index){
					if(value==null||value==""){
						return "";
					}
					return '<img src="'+value+'" onclick=window.open(\"'+value+'\") style="width:50px;height:50px">'
				};
			}
		}
        if(row.type=="imgs"){
            if(row.formatter==null){
                row.formatter = function(value,row,index){
                    if(value==null||value.trim()==""){
                        return "";
                    }
                    var html = "";
                    var urls = value.split(",");
                    for(var i =0;i<urls.length;i++){
                       html +=  '<img src="'+urls[i]+'" onclick=window.open(\"'+urls[i]+'\") style="width:50px;height:50px">';
                    }
                    return html;
                };
            }
        }
        row.sortable = true;
        if(row.rowHidden==null || row.rowHidden==false){
            finalColumn.push(row);
        }

	}
	var caozuo = finalColumn.contains('field','caozuo');	
	if(caozuo.find){
		if(caozuo.data.cusfor==null){
			caozuo.data.cusfor = caozuo.data.formatter;	
		}
		 
	} 
	if(setting.edit && setting.tree!=null){
		if(!caozuo.find){
			finalColumn.push({
				field:'caozuo',
				title:'操作'
			});
			caozuo = finalColumn.contains('field','caozuo');
		}
		caozuo.data.formatter = function(value,row,index){
			if(value=="caozuo"){
				return "";
			}
			var caozuoMethod = caozuo;
			var html = "";
			if(caozuo.data.cusfor!=null){
				html += caozuoMethod.data.cusfor(value,row,index);
			}
			if(setting.tree!=null){
				if(setting.add){
					html += '<a  class="pure-button pure-button-primary"  style="background: rgb(66, 184, 221);"  href="javascript:addSub();" >新增子节点</a>';
				}
			}


			return html;
		}
	}
    if(setting.editBtn==null||setting.editBtn===true){
        //html += '<a  class="pure-button pure-button-primary"  href="javascript:editMethod()">编辑</a>';
        if(setting.toolbar==null){
            setting.toolbar = [];
        }
        if(!isReload){

            setting.toolbar.push(
                {
                    text: '<a  class="pure-button pure-button-primary" >编辑</a>',
                    handler: function () {
                        editMethod();
                    }
                }
            );
        }

    }
    if(setting.del){
        if(setting.toolbar==null){
            setting.toolbar = [];
        }
        if(!isReload){
            setting.toolbar.push(
                {
                    text:'<a   class="pure-button pure-button-primary"  style="background: rgb(66, 184, 221); " >删除</a>',
                    handler: function () {
                        delMethod();
                    }

                }
            );
        }

    }
	setting.autoRowHeight = true;
	setting.singleSelect = setting.singleSelect==null?false:setting.singleSelect;
	setting.checkOnSelect = true;
	setting.selectOnCheck = true;
	setting.remoteSort = false;






    setting.columns = [finalColumn];
	setting.data = data;

	/** 开始easyui 的自适应操作 **/
    setting.fitColumns=true;
	for(var i = 0 ;i<finalColumn.length;i++){
	    var row = finalColumn[i];
	    if(row.width==null){
	        row.width = 80;
        }
    }
    /** 结束自适应 **/

	setting.onLoadSuccess = function(data) {
		if(setting.loadSuccess!=null){
			setting.loadSuccess(data);
		}
            var height =($(window).height()-$('#search_form').height());
		  if(setting.pager){
		      height -= ($('#pager').height()+2);
          }
            $('#grid').datagrid('resize',{
                height: height
            });


        var rows = $('#grid').datagrid('getRows');
        var hejiRows = [];
        
        for(var i =0 ;i<rows.length;i++){
        	if(rows[i].index==null){
        		continue;
        	}
        	if(rows[i].index =='合计'){
        		hejiRows.push(i);
        	}
        }
		if(setting.heji==null || setting.heji){
			if(hejiRows.length>1){
	        	for(var j = hejiRows.length-1 ; j > -1;j--){
	        		$('#grid').datagrid('deleteRow', hejiRows[j]);  
	        	}
	        }
	        if(setting.heji==null || setting.heji == true){
	        	 $('#grid').datagrid('appendRow', getStaticsData(finalColumn) );
	        }
		}
         
	    if(setting.frozenFinal){
	    	$('#grid').datagrid('freezeRow',$('#grid').datagrid('getRows').length-1);
	    }
	    if(setting.groupField!=null){
	    	if(setting.groupOpen==null || setting.groupOpen == true){
	    		$('#grid').datagrid('collapseGroup'); //设置折叠
	    	}
	    }
	    /*
        $('#grid').datagrid({
            fitColumns:true
        });*/


    };
	if(!isReload){
		var tol = [];
		if(setting.add){
			var btnName = "新增";
			if(setting.add.btnName!=null){
				btnName = setting.add.btnName;
			}
			tol = [{
				text : '<a  class="pure-button pure-button-primary" >'+btnName+'</a>',
				handler : function(){
					add(); 
				}
			}] 
		}
		 
		if(setting.toolbar!=null && setting.toolbar.length>0){
			for(var i =0 ;i<setting.toolbar.length;i++){
				tol.push(setting.toolbar[i])			
			}
		}
		if(tol.length==0){
			tol = null;
		}
		setting.toolbar = tol; 
	} 
 	if(setting.tree!=null){
 		setting.idField = tree.id;
 		setting.treeField = tree.treeField;

        /*styler : function(value, row, index) {
            return 'border:0;';
        }*/
        for(var i =0 ;i<setting.columns[0].length;i++){
            var row = setting.columns[0][i];
            row.styler = function(value, row, index) {
                return 'border:0;';
            };
        }
        $('#grid').treegrid(setting);
 		return ;
 	}

	$('#grid').datagrid(setting);
}  
 
function addSub(){
	editOrAdd(true,{
		sub:true
	});
}
function add(){
	var tree = null;
	if(setting.tree!=null){
		tree = {
			top:true	
		};
	}	
	editOrAdd(true,tree);
}
function editMethod(){
	editOrAdd(false)
}
var saving = false;
function editOrAdd(isAdd,treeSet){
	var title = "";
	if(isAdd){
		if(setting.add!=null && setting.add.src!=null){
			window.location.href = setting.add.src;
			return;
		}
		title = "新增";
	}else{
		title = "编辑";
	}
	clearForm();
	var row = getGridSelected();
	if(!isAdd){
		bindOrGetData(row);		
	}else{
		if(treeSet!=null){
			if(treeSet.top){
				$('#crud-'+setting.tree.pid).val(setting.tree.tpid);	
			}
			if(treeSet.sub){
				$('#crud-'+setting.tree.pid).val(row[setting.tree.id]);
			}
		}
	} 
	$('#crudDialog').dialog({
		title : title,
		width : crudDialogWidth,
		buttons : [{
			text : ' <a class="pure-button pure-button-primary" href="#" id="saveBtn" style="width: 100px;">保存</a>',
			handler : function() {
					var cols = column;
				 	var upateData = bindOrGetData();
				 	if(setting.beforeAjaxSave!=null){
				 		setting.beforeAjaxSave(upateData,cols);
				 	}
					 
					for(var i = 0;i<cols.length;i++){
						if(cols[i].required!=null && cols[i].required){
							var value = upateData[cols[i].field];
							if(value == null|| value ==""){
								$.messager.show({
						            title:'提示',
						            msg:cols[i].title+" 不能为空哦 ",
						            showType:'slide',
						            timeout:500,
						            style:{
						                right:'',
						                top:document.body.scrollTop+document.documentElement.scrollTop,
						                bottom:''
						            }
						        });
								return ;
							}
						}
					}
				 
				 if(saving){
					 return;
				 }
				 saving = true;
				 if(isAdd){
					 upateData.op = "add";
				 }else{
					 upateData.op = "save";					 
				 }
				 $.ajax({
				        url:searchUrl,
				        data:upateData,
				        dataType: "json", 
				        async:false,
                        method:"post",
				        success: function(res){
				        	if(res.code!=0){
				        		$.messager.show({
					                title:'提示',
					                msg:res.msg,
					                timeout:1000,
					                showType:'slide',
					                style:{
						                right:'',
						                top:document.body.scrollTop+document.documentElement.scrollTop,
						                bottom:''
						            }
					            });
				        	}else{
				        		if(setting.add.callback!=null){
				        			setting.add.callback();
				        		}
				        		$.messager.show({
					                title:'提示',
					                msg:res.msg,
					                timeout:500,
					                showType:'slide',
					                style:{
						                right:'',
						                top:document.body.scrollTop+document.documentElement.scrollTop,
						                bottom:''
						            }
					            });
					        	search();
					        	$('#crudDialog').dialog("close");
				        	} 
				        	saving = false;
				        }
			    });
			}
		}, {
			text : ' <a class="pure-button pure-button-primary" href="#"  style="width: 100px;">取消</a>',
			handler : function() {
				$('#crudDialog').dialog("close");
			}
		}]
	});
	 
	$("#crudDialog").panel("move",{top:$(document).scrollTop() + ($(window).height()-250) * 0.1}); 
	$('.window-shadow').hide();
	
	var divs = $("#crudDialog .pure-control-group");
	for(var i =0 ;i<divs.length;i++){
		var input = $(divs[i]).find('input');
		if($(divs[i]).css('display')=="block" && !input.prop('readonly')){
			input.focus();
			break;
		}
	}
}
function delMethod(){
	 var row = getGridSelected();
	 row.op = "del"; 
	 $.messager.confirm('提示', '确定要删除吗?', function(r){
         if (r){
        	 $.ajax({
     	        url:searchUrl,
     	        data:row,
     	        async:false,
                method:"post",
     	        dataType: "json", 
     	        success: function(res){
     	        	$.messager.show({
     	               title:'提示',
     	               msg:res.msg,
     	               showType:'slide',
     	               timeout:500,
     	               style:{
     	                   right:'',
     	                   top:document.body.scrollTop+document.documentElement.scrollTop,
     	                   bottom:''
     	               }
     	           });  
     	        	search();
     	        }
      		 }); 
         }
     }); 
	 $('.messager-window').css("top",$(document).scrollTop() + ($(window).height()-250) * 0.1);
	 $('.window-shadow').hide();
}
function getStaticsData(finalColumn){
	var res = {};
	for(var i = 0 ; i < finalColumn.length ; i++){
		var col = 	finalColumn[i];
		var field = col.field; 
		if(field == "index"){
			res[field] = '合计';
			continue;
		}
		if(field == "caozuo"){
			res[field] = 'caozuo';
			continue;
		}
		if(col.type=="number"){
			res[field] = compute(field);
		}else{
			res[field] = "";
		}
	}
	return res ;
}

function compute(key) {//计算函数
    var rows = $('#grid').datagrid('getRows')//获取当前的数据行
    var res = 0 ;
    for (var i = 0; i < rows.length; i++) {
    	var formatter = column.contains("field" ,key).data.formatter;
    	if(rows[i][key]==null || rows[i][key] == ""){
    		continue;
    	}
    	if( formatter != null){
    		res += parseFloat(formatter(rows[i][key],rows[i],i))
    	}else{
    		res += parseFloat(rows[i][key]);    		
    	}
   }
    res = (parseInt(res*100))/100
    return res;
}

function getGridSelected(){
	return $('#grid').datagrid('getSelected');
}
function getGridData(){
	return $('#grid').datagrid('getRows');
}
function getGridChecked(){
	return $('#grid').datagrid('getChecked');
}
var isReload = false;
function search(){
	isReload = true;
	setting.initSearch = true;
	createQuery(queryId,column,setting,searchUrl);
}
function getSearch(){
	var searchParams = fixSearch;
	 $('#search_form').find('.searchInput').each(function(){
		 var $this = $(this);
		 var type = $this.data('type');
		 var field = $this.data('field');
		 var condition=$this.attr("condition");
		 var op = $this.data('op');
		 var attrType = $this.attr('type');
		 var col = colMap[field];


                 if(condition != null && condition == "true"){
                     var value = "";
                     if($this.attr('type')=="checkbox"){
                         value = $this.prop('checked');
                     }else{
                         value = $this.val();
                     }
                     searchParams["search_"+op+"_"+field]=value;
                 }

                 if(type == "date"){
                     var placeHolder = $this.attr('placeHolder');
                     var hasTime = ($this.val().indexOf(':')>=0);
                     if(!hasTime &&  $this.val()!=""){
                         if(placeHolder=="起"){
                             $this.val($this.val()+" 00:00")
                         }else{
                             $this.val($this.val()+" 23:59")
                         }
                     }
                     searchParams["search_"+op+"_"+field]=$this.val();
                 }else{

                     var value = $this.val();
                     /*if($this.parent().find('.textbox-value').length > 0){
                         $this.parent().find('.textbox-value').each(function(){
                             value += $(this).val()+",";
                         });
                         value = value.substr(0,value.length-1);
                         console.log($this.val());*/
                     //}else{
                         value = $this.val();
                     //}
                     //console.log($('#search-'+field).val());

                     if(attrType=="radio"){

                         value = $(this).parent().find("input[type='radio']:checked").data('value');


                     }


                     searchParams["search_"+op+"_"+field]=value;
                 }




	});
    if(setting.pager){
        searchParams.page = page-1;
        searchParams.size = size;
    }


	return searchParams;
}
 
Array.prototype.groupBy = function(field){
	var result = {};
	for(var i =0 ;i<this.length;i++){
		var row = this[i];
		var fieldValue=  row[field];
		if(result.length==0){
			result[fieldValue] = [];
    		result[fieldValue].push(row);
		}
		var find = false;
		for(key in result){
			if(fieldValue==key){
				find = true;
				result[key].push(row);
				break;
			}
		}
		if(find){
			continue;
		}
		result[fieldValue] = [];
		result[fieldValue].push(row);
	}
	return result;
};
 

function arrayToString(array){
    var ids = "";
    for(var i =0 ;i<array.length;i++){
       ids += array[i];
       if(i<array.length-1){
           ids += ",";
       }
    }
    return ids;
}

$(function () {
    $.ajaxSetup({
        layerIndex:-1,
        beforeSend: function () {
            this.layerIndex = layer.load(0, { shade: [0.5, '#393D49'] });
        },
        complete: function () {
            layer.close(this.layerIndex);
        },
        error: function () {
            layer.alert('请稍后再试', {
                skin: 'layui-layer-molv'
                , closeBtn: 0
                , shift: 4 //动画类型
            });
        }
    });
});
function postAsyncFalse(url,data,callback) {
    $.ajax({
        url: url,
        data:data,
        async:false,
        method:"post",
        dataType: "json",
        success: function(res){
            callback(res);
        }
    });
}
function postAsync(url,data,callback) {
    $.ajax({
        url: url,
        data:data,
        async:true,
        method:"post",
        dataType: "json",
        success: function(res){
            callback(res);
        }
    });
}

</script>

<style>

</style>